//
//  FIndPasswordViewController.m
//  YYPHSpeedJump
//
//  Created by sujiang on 15/12/18.
//  Copyright © 2015年 sujiang. All rights reserved.
//

#import "FIndPasswordViewController.h"
#import "RegistInfoView.h"
#import "LableAndTextField.h"
#import "UserModel.h"
@interface FIndPasswordViewController ()<UITextFieldDelegate>
{
    LableAndTextField *phoneNumView;
    RegistInfoView *authCodeView;
    RegistInfoView *passwordView;
    RegistInfoView *passAgainView;
    UIButton *authCodeBtn;
}

@property (nonatomic, strong) NSMutableString *str;
@property (nonatomic, strong) NSString *placeHolder;
@property (nonatomic, strong) UIButton *confirmBtn;
@property (nonatomic, strong) NSTimer *timer;

@end

@implementation FIndPasswordViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self addSubViews];
    self.view.backgroundColor = kColors(239, 239, 244, 1);

}

- (NSMutableString *)str
{
    if (!_str) {
        _str = [NSMutableString string];
    }
    return _str;
}

- (void)addSubViews
{
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"navigationBg"] forBarMetrics:(UIBarMetricsDefault)];
    self.navigationItem.title = @"找回密码";
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName : [UIColor whiteColor]}];
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"fanhui"] style:(UIBarButtonItemStylePlain) target:self action:@selector(actionBack:)];
    self.navigationItem.leftBarButtonItem.tintColor = kColors(255, 255, 255, 1);
    phoneNumView = [[LableAndTextField alloc] initWithFrame:CGRectMake(0, 7, kScreenWidth, 34) lableText:@"+86" placeHolderText:@"请输入手机号"];
    [self.view addSubview:phoneNumView];
    phoneNumView.textField.delegate = self;

    
    authCodeView = [[RegistInfoView alloc] initWithFrame:CGRectMake(0, phoneNumView.bottom + 7, kScreenWidth, 34) placeHolder:@"请输入验证码"];
    authCodeBtn = [UIButton buttonWithType:(UIButtonTypeCustom)];
    authCodeBtn.frame = CGRectMake(kScreenWidth - 80, 6, 71, 22.5);
    [authCodeView addSubview:authCodeBtn];
    authCodeBtn.backgroundColor = kColors(131, 131, 131, 1);
    [authCodeBtn setTitleColor:kColors(255, 255, 255, 1) forState:(UIControlStateNormal)];
    authCodeBtn.titleLabel.font = [UIFont systemFontOfSize:12];
    [authCodeBtn setTitle:@"获取验证码" forState:(UIControlStateNormal)];
    [authCodeBtn addTarget:self action:@selector(actionGetAuthcode:) forControlEvents:(UIControlEventTouchUpInside)];
    [self.view addSubview:authCodeView];
    authCodeBtn.userInteractionEnabled = NO;
    authCodeBtn.layer.cornerRadius = 5;
    
    passwordView = [[RegistInfoView alloc] initWithFrame:CGRectMake(0, authCodeView.bottom + 7, kScreenWidth, 34) placeHolder:@"请输入新密码，6~20位"];
    passwordView.textField.secureTextEntry = YES;
    [self.view addSubview:passwordView];
    
    passAgainView = [[RegistInfoView alloc] initWithFrame:CGRectMake(0, passwordView.bottom + 7, kScreenWidth, 34) placeHolder:@"请再次输入新密码，6~20位"];
    passAgainView.textField.secureTextEntry = YES;
    [self.view addSubview:passAgainView];
    
    self.confirmBtn = [UIButton buttonWithType:(UIButtonTypeCustom)];
    self.confirmBtn.frame = CGRectMake((kScreenWidth - 332 * kWidthScale) / 2, passAgainView.bottom + 10, 332 * kWidthScale, 33);
    [self.view addSubview:self.confirmBtn];
    [self.confirmBtn setTitleColor:kColors(255, 255, 255, 1) forState:(UIControlStateNormal)];
    [self.confirmBtn setTitle:@"确认修改" forState:(UIControlStateNormal)];
    [self.confirmBtn addTarget:self action:@selector(confirmBtnAct:) forControlEvents:UIControlEventTouchUpInside];
    self.confirmBtn.backgroundColor = kColors(218, 166, 46, 1);
    self.confirmBtn.layer.cornerRadius = 5;
}


#pragma mark -- 代理方法
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    self.placeHolder = textField.placeholder;
    textField.placeholder = nil;
}

- (void)textFieldDidEndEditing:(UITextField *)textField
{
    if ([textField.text isEqualToString:@""]) {
        textField.placeholder = self.placeHolder;
    }
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if ([string  isEqual: @""] && self.str != nil) {
        self.str = (NSMutableString *)[self.str substringToIndex:[self.str length] - 1];
    } else {
        self.str = [NSMutableString stringWithFormat:@"%@%@", self.str, string];
    }
    
    if ([self.str checkPhoneNumInput] == YES) {
        [authCodeBtn setBackgroundColor:kColors(218, 166, 46, 1)];
        authCodeBtn.userInteractionEnabled = YES;
    } else {
        [authCodeBtn setBackgroundColor:kColors(131, 131, 131, 1)];
        authCodeBtn.userInteractionEnabled = NO;
    }
    
    
    return YES;
}


#pragma mark -- 按钮点击事件
- (void)actionBack:(UIBarButtonItem *)leftBar
{
    [self.navigationController popViewControllerAnimated:YES];
}


- (void)actionGetAuthcode:(UIButton *)button
{
    // 点击获取验证码
    /**
     *  1分钟倒计时
     *  按钮文字换成重新获得验证码
     */
    NSDictionary *dict = @{@"phone": phoneNumView.textField.text};
    [NetworkHandle getInfoWithUrl:[NSString stringWithFormat:@"%@%@", kBaseUrl, kForgetInvate] dictionary:dict success:^(NSDictionary *dictionary) {
        NSLog(@"%@", dictionary);
    }];
    
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(secondCount) userInfo:nil repeats:YES];
    [self.timer fire];
}
- (void)secondCount
{
    static NSInteger time = 60;
    [authCodeBtn setTitle:[NSString stringWithFormat:@"%ld", time] forState:(UIControlStateNormal)];
    time--;
    if (time < 0) {
        [self.timer invalidate];
        [authCodeBtn setTitle:@"重新获取" forState:(UIControlStateNormal)];
        time = 60;
    }
}

//确认修改    
- (void)confirmBtnAct:(UIButton*)button
{
    if ([passwordView.textField.text isEqualToString:passAgainView.textField.text] && passwordView.textField.text.length >= 6) {
        NSString *string = [NSString stringWithFormat:@"%@%@", kBaseUrl, kForgetOK];
        NSDictionary *dict = @{@"phone":phoneNumView.textField.text, @"sms_code":authCodeView.textField.text, @"new_password":passwordView.textField.text, };
        // &phone=XXXX&sms_code=888880&password=XXXXXX&invite_code=XXXX
        [NetworkHandle registAndLoginByUrl:string dict:dict success:^(NSDictionary *dictionary) {
            if ([dictionary[@"code"] isEqualToString:@"200"]) {
               
                [Tools showAlert:@"密码修改成功"];
                [self.navigationController popViewControllerAnimated:YES];
            } else {
                [Tools showAlert:dictionary[@"输入信息错误"]];
            }
            
        }];
        

    }else{
        [Tools showAlert:@"两次输入密码不一致"];
    }
    
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
